package work.shyk.cts.demo;

import com.atlassian.httpclient.apache.httpcomponents.DefaultHttpClientFactory;
import com.atlassian.httpclient.api.HttpClient;
import com.atlassian.jira.rest.client.AuthenticationHandler;
import com.atlassian.jira.rest.client.IssueRestClient;
import com.atlassian.jira.rest.client.JiraRestClient;
import com.atlassian.jira.rest.client.ProjectRestClient;
import com.atlassian.jira.rest.client.auth.BasicHttpAuthenticationHandler;
import com.atlassian.jira.rest.client.domain.BasicProject;
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClient;
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory;
import com.atlassian.jira.rest.client.internal.async.AsynchronousProjectRestClient;
import com.atlassian.util.concurrent.Promise;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.nio.client.HttpAsyncClient;
import org.apache.http.nio.conn.ClientAsyncConnectionManager;
import org.apache.http.nio.conn.scheme.AsyncScheme;
import org.apache.http.nio.conn.scheme.AsyncSchemeRegistry;
import org.apache.http.nio.conn.ssl.SSLLayeringStrategy;
import org.python.modules._marshal;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * description: <br>
 * createTime: 2020/9/39:19 <br>
 *
 * @author zzh
 */
public class JiraDemo {

    public static <T> T getField(Object obj, String fieldName) throws NoSuchFieldException, IllegalAccessException {
        Class<?> aClass = obj.getClass();
        Field field = aClass.getDeclaredField(fieldName);
        field.setAccessible(true);
        T result = (T) field.get(obj);
        field.setAccessible(false);
        return result;
    }

    public static <T> T getSuperField(Object obj, String fieldName) throws NoSuchFieldException, IllegalAccessException {
        Class<?> aClass = obj.getClass();
        Field field = aClass.getSuperclass().getDeclaredField(fieldName);
        field.setAccessible(true);
        T result = (T) field.get(obj);
        field.setAccessible(false);
        return result;
    }

    public static void setFinalFiled (Object obj, String fieldName, Object newValue) throws NoSuchFieldException, IllegalAccessException {
        Class<?> aClass = obj.getClass();
        Field field = aClass.getDeclaredField(fieldName);
        field.setAccessible(true);
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        System.out.println(modifiersField.getModifiers());
        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
        field.set(obj, newValue);
        modifiersField.setInt(field, field.getModifiers() & Modifier.FINAL);
        System.out.println(modifiersField.getModifiers());
        modifiersField.setAccessible(false);
        field.setAccessible(false);
    }

    public static void main(String[] args) throws URISyntaxException, NoSuchFieldException, IllegalAccessException, KeyManagementException, NoSuchAlgorithmException, IOException {
//        AsynchronousJiraRestClient client = new AsynchronousJiraRestClient(new URI("http://jira.pcitc.com/"), new BasicHttpAuthenticationHandler("cdp.yk", "YkCdp110^"));
//        AsynchronousJiraRestClient client = new AsynchronousJiraRestClient(new URI("http://jira.pcitc.com/"), new CookieAuthenticationHandler("pcitc.crowd.token=fj0wJ4ac97UZBS01dHZfVg00; "));
        CookieAuthenticationHandler.setToken("pcitc.crowd.token=fj0wJ4ac97UZBS01dHZfVg00; ");
        final AsynchronousJiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
        URI jiraServerUri = new URI("http://jira.pcitc.com/");
        JiraRestClient client = factory.create(jiraServerUri, new CookieAuthenticationHandler());
        ProjectRestClient projectRestClient = client.getProjectClient();
        HttpClient c = getSuperField(projectRestClient, "client");
        HttpAsyncClient c1 = getField(c, "nonCachingHttpClient");
        ClientAsyncConnectionManager c2 = getSuperField(c1, "connmgr");
        AsyncSchemeRegistry registry = getSuperField(c2, "schemeRegistry");
        AsyncScheme https = registry.get("https");
        SSLContext ctx = SSLContext.getInstance("SSL");
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }


            @Override
            public void checkServerTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }


            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        ctx.init(null, new TrustManager[]{tm}, null);

        registry.register(
                new AsyncScheme("https", 443, new SSLLayeringStrategy(ctx, new AllowAllHostnameVerifier())));
        Promise<Iterable<BasicProject>> allProjects = projectRestClient.getAllProjects();
        AtomicInteger counter = new AtomicInteger(0);allProjects.claim();
        allProjects.done((it) -> {
            it.forEach((p) -> {
                System.out.println(counter.addAndGet(1) + " :\t" + p.getKey());
            });
        });

        IssueRestClient issueRestClient = client.getIssueClient();
//        HttpClient c3 = getSuperField(issueRestClient, "client");
//        HttpAsyncClient c4 = getField(c, "nonCachingHttpClient");
//        ClientAsyncConnectionManager c5 = getSuperField(c1, "connmgr");
//        AsyncSchemeRegistry registry1 = getSuperField(c2, "schemeRegistry");
//        System.out.println(c == c3);
//        System.out.println(c1 == c4);
//        System.out.println(c2 == c5);
//        System.out.println(registry == registry1);
        try(FileInputStream inputStream = new FileInputStream("C:\\Users\\zzh\\Desktop\\redis.conf")) {
            Promise<Void> voidPromise = issueRestClient.addAttachment(new URI("https://jira.pcitc.com/rest/api/latest/issue/94547/attachments"), inputStream, "redis.conf");
            System.out.println(voidPromise.getClass().getName());
            voidPromise.claim();
            voidPromise.fail((e) -> {
                e.printStackTrace();
            });
            voidPromise.done((r) -> System.out.println(Thread.currentThread().getName() + " : done"));
        }
        System.out.println("over");
    }
}
